package ar.edu.itba.it.pdc.utils;

import java.util.LinkedList;
import java.util.List;

import org.joda.time.DateTime;

import ar.edu.itba.it.pdc.app.Madonna3;
import ar.edu.itba.it.pdc.app.config.mapping.Restriction;
import ar.edu.itba.it.pdc.app.config.mapping.Server;

public class UserRestrictions {
	
	private static List<Restriction> restrictions = Madonna3.getApp().getSettings().getProxy().getUserRestrictions().getUserRestriction();
	
	public static boolean checkIntervals(String username) {
		DateTime now = new DateTime();
		List<Restriction> restrictions = getRestrictions(username);
		for(Restriction r : restrictions)
			if(r.getInterval() != null) {
				DateTime f = TimeConverter.parseHour(r.getInterval().getFrom());
				DateTime t = TimeConverter.parseHour(r.getInterval().getTo());
				DateTime from = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), f.hourOfDay().get(), f.minuteOfHour().get(), f.secondOfMinute().get(), f.millisOfSecond().get());
				DateTime to = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), t.hourOfDay().get(), t.minuteOfHour().get(), t.secondOfMinute().get(), t.millisOfSecond().get());

				if(now.isBefore(from) || now.isAfter(to))
					return false;
				else
					return true;
			}
		return true;		
	}
	
	private static List<Restriction> getRestrictions(String username) {
		List<Restriction> ret = new LinkedList<Restriction>();
		
		for(Restriction r : restrictions) {
			if(userIsIn(r.getUserList(), username)) {
				ret.add(r);
			}
		}
		
		return ret;
	}
	
	private static boolean userIsIn(String userList, String username) {
		if(userList != null) {
			String users[] = userList.split(",");
			for(String u : users) {
				if(u.equals(username)){
					return true;
				}
			}
		}
		return false;
	}
	
	public static boolean checkHits(String username, int n){
		List<Restriction> restrictions = getRestrictions(username);
		for(Restriction r : restrictions) {
			if(r.getHits() != null && n > r.getHits()) {
				return false;
			}
		}
		return true;
	}
	
	public static Server changeServer(String username) {
		List<Restriction> restrictions = getRestrictions(username);
		for(Restriction r : restrictions) {
			if(r.getServer() != null) {
				return r.getServer();
			}
		}
		return null;
	}
	
}
